import { useState, useEffect } from 'react';
import { Card, Popover, Pagination, Spin, Popconfirm, message } from 'antd';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import { queryKnowledgeList, deleteKnowledge } from '@/services/knowledge';
import CardItem from '@/components/CardItem';
import AddKnowledgeModel from '../components/addKnowledgeModel/index';
import ManagerModel from '../components/managerModel/index';

import styles from './style.less';

const KnowledgeList: React.FC = () => {
  const [totals, setTotals] = useState(0);
  const [pagesize, setPagesize] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  const [spining, setSpining] = useState(false);

  const [cardList, setCardList] = useState([]);
  const [managerVisible, setManagerVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false);
  const [modelTitle, setModelTitle] = useState('');
  const [modelItem, setModelItem] = useState<API.KnowledgeListItem>();

  // 获取知识库列表
  const getKnowledgeList = async () => {
    setSpining(true);
    const res = await queryKnowledgeList({
      pageNum: currentPage,
      pagesize: pagesize,
    });
    const { code, data } = res || {};
    setSpining(false);

    if (!code && data) {
      setCardList(data.records as any);
      setTotals(data.total);
      setPagesize(data.size);
      setCurrentPage(data.current);
    }
  };

  useEffect(() => {
    getKnowledgeList();
  }, []);

  // 知识库-新增
  const hanldleAddKuFather = () => {
    history.push(`/knowledge/detail/add`);
  };

  // 查看--知识库知识列表
  const toKnowledgeDataList = (id: number) => {
    history.push(`/knowledge/data/list/edit/${id}`);
  };

  // 权限--关联管理员
  const openManageModel = (item: any) => {
    setModelItem(item);
    setManagerVisible(true);
  };

  //打开新增知识库弹窗--分三种
  const openAddModel = (item: any, nameType: string) => {
    setAddVisible(true);
    setModelItem(item);
    setModelTitle(nameType);
  };

  // 新增气泡显示
  const btnsContent = (item: any) => (
    <div style={{ width: '100px', textAlign: 'center' }}>
      <p className={styles['label-a']} onClick={() => openAddModel(item, '上传文档')}>
        上传文档
      </p>
      <p className={styles['label-a']} onClick={() => openAddModel(item, '在线编辑')}>
        在线编辑
      </p>
      <p className={styles['label-a']} onClick={() => openAddModel(item, '导入链接')}>
        导入链接
      </p>
    </div>
  );

  // 分页
  const onChangePagination = (page: number, pageSize: number) => {
    setCurrentPage(page);
    setPagesize(pageSize);
    getKnowledgeList();
  };

  // 删除知识库
  const toDeleteKnowledge = async (ids: string) => {
    const res = await deleteKnowledge({ id: ids });
    if (!res.code && res.data) {
      message.success('删除成功');
      getKnowledgeList();
    }
  };

  return (
    <PageContainer>
      <Card title="">
        {spining ? (
          <Spin style={{ width: '100%' }} />
        ) : (
          <div>
            <div className={styles.container}>
              <CardItem
                title="新增知识库"
                desc="创建知识库，补充新知识"
                isAdd
                onAdd={hanldleAddKuFather}
              />
              {cardList &&
                cardList.map((item: any, index) => (
                  <CardItem title={item.name} key={`${item.name + index}`} desc={item.description}>
                    <div></div>
                    <div>
                      <a className={styles['label-a']} onClick={() => toKnowledgeDataList(item.id)}>
                        查看
                      </a>
                      <Popover placement="bottom" content={btnsContent(item)} title={null}>
                        <a className={styles['label-a']}>新增</a>
                      </Popover>
                      <a className={styles['label-a']} onClick={() => openManageModel(item)}>
                        权限
                      </a>
                      <Popconfirm
                        key="delete"
                        title={`确认删除知识库${item?.name}？`}
                        onConfirm={() => toDeleteKnowledge(item.id)}
                      >
                        <a className={styles['label-a']}>删除</a>
                      </Popconfirm>
                    </div>
                  </CardItem>
                ))}
            </div>
            <div style={{ display: 'flex', justifyContent: 'right' }}>
              <Pagination
                total={totals}
                showTotal={(total) => `共 ${total} 条`}
                defaultPageSize={pagesize}
                defaultCurrent={currentPage}
                onChange={onChangePagination}
              />
            </div>
          </div>
        )}

        {/* 新增弹窗 */}
        <AddKnowledgeModel
          addVisible={addVisible}
          modelTitle={modelTitle}
          modelItem={modelItem}
          closeModel={() => setAddVisible(false)}
          type="add"
        />
        {/* 权限设置-管理员弹窗 */}
        <ManagerModel
          managerVisible={managerVisible}
          managerId={modelItem?.id || ''}
          managerTitle="权限设置"
          closeModel={() => setManagerVisible(false)}
        />
      </Card>
    </PageContainer>
  );
};

export default KnowledgeList;
